<template>
    <div style="margin-top:10px;margin-left:10px">
    <el-row :gutter="15">
        <el-col :span="2">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="addRoleDialog()">新增</el-button>
        </el-col>
        <el-col :span="2">
            <el-button size="mini" type="info" icon="el-icon-info" @click="infoDialogVisible=true">说明信息</el-button>
        </el-col>
    </el-row>
    
    <el-table :data="groupAndRole" border style="width: 99%;margin-bottom: 20px;margin-top:10px;margin-right:20px" 
    default-expand-all :tree-props="{children: 'roles'}" row-key='id' :row-class-name="tableRowClassName"
    :header-cell-style="{'text-align':'center'}" >
        <el-table-column label="分组名称" prop="roleGroupName"></el-table-column><!--  索引页  -->
        <el-table-column label="角色名称" prop="roleName"></el-table-column><!--  索引页  -->
        <el-table-column label="权限字符" prop="permission"></el-table-column><!--  索引页  -->
        <el-table-column label="下载次数限制" prop="timesLimited"></el-table-column><!--  索引页  -->
        <el-table-column label="创建时间" prop="createTime" ></el-table-column><!--  索引页  -->
        <el-table-column label="修改时间" prop="updateTime"></el-table-column><!--  索引页  -->
        <el-table-column label="修改人" prop="modifyUser"></el-table-column><!--  索引页  -->
        <el-table-column label="备注" prop="remark"></el-table-column><!--  索引页  -->
        <el-table-column label="操作" width="120px">
        <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit"  size="mini" @click="showEditDialog(scope.row)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete"  size="mini" @click="deleteGroupRole(scope.row)"></el-button>
            <!-- <el-button type="primary" size="mini" v-show="!isGroup(scope.row)" icon="iconfont icon-quanxian" @click="showEditDialog(scope.row)"></el-button> -->
        </template>
        </el-table-column>
    </el-table>

    <el-dialog :visible.sync="addRoleDialogVis" title="添加角色" width="500px">
        <el-tabs v-model="activeName">
            <el-tab-pane label="添加角色分组" name="first">
                <el-form :model="addGroupForm" ref="addGroupFormRef" label-width="auto" label-position="left" :inline= false :rules="addGroupRules">
                    <el-form-item label="分组名称" prop="roleGroupName">
                        <el-input placeholder="请填写角色名称" v-model="addGroupForm.roleGroupName"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input placeholder="请填写备注" v-model="addGroupForm.remark"></el-input>
                    </el-form-item> 
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="添加角色" name="second">
                <el-form :model="addRoleForm" ref="addRoleFormRef" label-width="auto" label-position="left" :inline= false :rules="addRoleRules">
                    <el-form-item label="角色名称" prop="roleName" >
                        <el-input placeholder="请填写角色名称" v-model="addRoleForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="所属分组" prop="roleGroupName">
                        <el-select  placeholder="请选择分组" v-model="addRoleForm.roleGroupName" style="width:353px">
                        <el-option v-for="group in groupList" :key="group.id" :label="group.roleGroupName" :value="group.roleGroupName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="下载次数限制" prop="downloadlimit" >
                        <el-input placeholder="请填写下载次数限制" v-model="addRoleForm.downloadlimit"></el-input>
                    </el-form-item>
                    <el-form-item label="权限列表" prop="permissionList" multiple  >
                        <my-tree ref="premissionTree" ></my-tree>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input placeholder="请填写备注" v-model="addRoleForm.remark"></el-input>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        
        <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleDialogVis = false">取 消</el-button>
            <el-button type="primary" @click="addSth()">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog :visible.sync="infoDialogVisible" width="565px" height="550px" title="角色管理说明">
        <span>
            角色管理是对权限类型的管理，可以添加、删除、修改<br />
            <el-divider></el-divider>
            <font color="#dd0000">分组：分组是对角色的分类管理</font><br />
            <font color="#dd00dd">角色：同一角色下的用户拥有相同的访问权限，包括：访问页面控制、下载量限制等</font><br />
            <img src="@/assets/images/role.svg" alt="架构图" width="500px">
        </span>
    </el-dialog>
    <!-- 修改分组信息对话框 -->
    <el-dialog :visible.sync="editGroupDialogVis" title="修改分组信息" width="500px">
        <el-form :model="addGroupForm" ref="addGroupFormRef" label-width="100px" :rules="addGroupRules">
            <el-form-item prop="roleGroupName" label="分组名称" required>
                <el-input v-model="addGroupForm.roleGroupName" placeholder="修改分组名称"></el-input>
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input v-model="addGroupForm.remark" placeholder="修改分组备注"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editGroupDialogVis = false">取 消</el-button>
            <el-button type="primary" @click="editGroup()">提 交</el-button>
        </span>
    </el-dialog>
    <!-- 修改角色信息对话框 -->
    <el-dialog :visible.sync="editRoleDialogVis" title="修改角色信息" width="500px">
        <el-form :model="addRoleForm" ref="addRoleFormRef" label-width="100px" :rules="addRoleRules">
            <el-form-item prop="rolename" label="角色名称">
                <el-input v-model="addRoleForm.roleName" placeholder="修改角色名称"></el-input>
            </el-form-item>
            <el-form-item prop="downloadlimit" label="下载限制">
                <el-input v-model="addRoleForm.downloadlimit" placeholder="修改下载限制"></el-input>
            </el-form-item>
            <el-form-item prop="permissionList" label="权限列表">
                <my-edittree ref="editTree"></my-edittree>
            </el-form-item>
            <el-form-item label="所属分组" prop="roleGroupId">
                <el-select  placeholder="请选择分组" v-model="addRoleForm.roleGroupName" style="width:353px">
                <el-option v-for="group in groupList" :key="group.id" :label="group.roleGroupName" :value="group.roleGroupName"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVis = false">取 消</el-button>
            <el-button type="primary" @click="editRole()">提 交</el-button>
        </span>
    </el-dialog>
    </div>
</template>

<script>
import { addRoleGroupApi, addRoleApi, getGroupAndRoleApi,
         getAllRoleGroupApi, editGroupApi, editRoleApi, 
         deleteGroupApi, deleteRoleApi, assignPermissionsApi,
         getPermissionByRoleIdApi } from '@/api/roles/roles'
import PermissionTree from '@/components/PermissionTree/index.vue'
import editTree from '@/components/PermissionTree/index.vue'
import qs from 'qs'
export default {
    components:{
        'my-tree': PermissionTree,
        'my-edittree':editTree
    },
    data() {
        return {
            addRoleDialogVis:false,
            infoDialogVisible:false,
            editGroupDialogVis:false,
            editRoleDialogVis:false,
            
            rolePermission:{    //为角色绑定权限
                roleId:0,
                permissionIds: []
            },

            activeName: 'first', //tabs默认

            addGroupForm:{
                roleGroupName:"",
                remark:"",
            },

            addRoleForm:{
                roleName:"",
                downloadlimit:"",
                permissionIds:[],
                roleGroupId:"",
                roleGroupName:"",
                remark:"",
            },

            groupAndRole: [],  //表格数据
            groupList:[],   //已有的分组集合
            addGroupRules:{
                roleGroupName: [
                    { required: true, message: '请输入分组名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            },
            addRoleRules:{
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                downloadlimit: [
                    { required: true, message: '请输入下载限额', trigger: 'blur' },
                    { min: 1, max: 5, message: '长度在 1 到 5 位数字', trigger: 'blur' }
                ],
                roleGroupName: [
                    { required: true, message: '请选择所属分组', trigger: 'blur' },
                ],
            }

            
        }
    },
    methods:{
        tableRowClassName({row}){
            
            if(row.roleGroupName === undefined){
                return ''
            }else{
                return 'group-row'
            }
            
        },
        getAllGroup(){
            getAllRoleGroupApi().then(res=>{
                this.groupList = res.data.roleGroups
            })
        },
        addRoleDialog(){
            this.addRoleDialogVis = true;
            
        },
        submitRole(){
            this.addRoleDialogVis = false;
        },
        isGroup(row){ 
            if(row.roleGroupName === undefined){
                return false
            }else{
                return true
            }
        },
        getAll(){
            getGroupAndRoleApi().then(res=>{
                //this.$message.success('成功')                 //debug
    
                let groupAndRole = res.data.groupAndRole;
                groupAndRole.forEach(e=>{
                    e.id += 10000
                })
                this.groupAndRole = groupAndRole;
            })
        },
        addSth(){
            if(this.activeName === 'first'){
                this.addRoleGroup()
            }else if(this.activeName === 'second'){
                this.addRole();
            }else{
                this.$message.error('未知错误，请刷新浏览器重试')
                this.addRoleDialogVis = false
                this.getAll()
            }
        },
        addRole(){
            this.$refs.addRoleFormRef.validate((valid)=>{
                this.addRoleForm.permissionIds = this.$refs.premissionTree.getCheckedNodes()
                if(valid && this.addRoleForm.permissionIds.length){
                    addRoleApi(this.addRoleForm).then(res=>{
                        this.$message.success(res.message)
                        this.addRoleDialogVis = false
                        this.getAll()
                        this.$refs.addRoleFormRef.resetFields()
                    })
                }else{
                    this.$message.error('带*为必填项')
                    return;
                }
            })
            
        },
        addRoleGroup(){
            this.$refs.addGroupFormRef.validate((valid) =>{
                if(valid){
                    addRoleGroupApi(this.addGroupForm).then(res=>{
                        this.$message.success(res.message)
                        this.addRoleDialogVis = false
                        this.getAll()
                        this.$refs.addGroupFormRef.resetFields()
                    })
                }
            })
        },
        showEditDialog(row){
            if(row.roleGroupName == undefined){
                getPermissionByRoleIdApi(row.id).then(res=>{
                    var arr = new Array();
                    res.data.permissions.forEach(e=>{
                        arr.push(e.id)
                    })
                    setTimeout(()=>{
                        this.$refs.editTree.setCheckedKeys(arr)
                    },100)
                    console.log("children")
                    this.editRoleDialogVis = true
                    this.addRoleForm = JSON.parse(JSON.stringify(row))
                    this.addRoleForm.roleGroupName = this.findParent(row.id)
                })
                
            }else{
                console.log("parent")
                this.editGroupDialogVis = true
                this.addGroupForm = JSON.parse(JSON.stringify(row))
            }
        },
        findParent(id){
            var res
            this.groupAndRole.forEach(e=>{
                e.roles.forEach(element=>{
                    if(element.id == id){
                        res = e.roleGroupName
                    }
                })
            })
            return res
        },
        editGroup(){
            this.addGroupForm.id -= 10000;
            editGroupApi(this.addGroupForm).then(res=>{
                this.$message.success(res.message)
                this.getAll()
                this.editGroupDialogVis = false
            })
        },
        editRole(){
            this.addRoleForm.permissionIds = this.$refs.editTree.getCheckedNodes()
           // this.rolePermission.roleId = this.addRoleForm.id
            editRoleApi(this.addRoleForm).then(res=>{
                this.$message.success(res.message)
            })
            this.getAll()
            this.editRoleDialogVis = false
        },
        deleteGroupRole(row){
            if(row.roleGroupName === undefined){
                console.log("children")
                this.deleteRole(row.id)
            }else{
                console.log("parent")
                this.deleteGroup(row.id)
            }
        },
        deleteGroup(id){
            this.$confirm('是否确定删除该分组，若删除该分组相关的角色信息将一并删除，请谨慎操作！','确认消息',{
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                deleteGroupApi(id).then(res=>{
                    this.$message.success(res.message)
                    this.getAll()
                })
            }).catch(()=>{
                this.$message.info('已取消删除')
            })
        },
        deleteRole(id){
            this.$confirm('是否确定删除该角色?若删除该角色信息,拥有该角色信息的帐户将无法使用，请谨慎操作！','确认消息',{
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            }).then(()=>{
                deleteRoleApi(id).then(res=>{
                    this.$message.success(res.message)
                    this.getAll()
                })
            }).catch(()=>{
                this.$message.info('已取消删除')
            })
        },
    },
    computed:{
        
    },
    created() {
        this.getAll()
        this.getAllGroup()
    },
}
</script>

<style lang="less" scoped>
/deep/.el-table .group-row{
    background: #e8f4f5;
}
</style>